package main


import (
	"fmt"
	"log"
	"net/http"
	"time"
)
var ch = make(chan http.ResponseWriter)




func Hello(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	//w.Write([]byte("Hello!!\n"))
	//time.Sleep(10 * time.Second)
	w.(http.Flusher).Flush()
	ch <- w
}

func do(ch chan http.ResponseWriter){
	for{
		w := <- ch
		time.Sleep(10*time.Second)
		fmt.Println(1111)
		w.Write([]byte{123})
	}


}

func main() {
	http.HandleFunc("/hello", Hello)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("x-request-id", "x-request-id")

		f, _ := w.(http.Flusher)

		for i := 0; i < 5; i++ {
			fmt.Fprintf(w, "time.now(): %v \n", time.Now())  //这里一定要加\n分隔符，方便客户端分次获取
			f.Flush()    //每隔一秒向客户端 flush 当前时间
			time.Sleep(time.Second)
		}
		time.Sleep(5*time.Second)
		fmt.Println("finished")
	})


	go do(ch)

	log.Fatal(http.ListenAndServe(":30000", nil))
}

//再hello方法中,ResponseWriter.Write只是将数据写进了一个缓冲区，如过缓冲区未被写满是不会往tcp连接里写的，表现为包没发出去。http server会在Handler函数结束后调用Flush，所以在Handler函数里的任何阻塞行为都会影响到回包数据的发送.这种情况下需要主动调用Flash()

// curl -i http://127.0.0.1:30000 时,终端会1秒打印一个时间,并且头部会打印Transfer-Encoding: chunked
